package cn.tedu.account.tcc;

import cn.tedu.account.entity.Account;
import cn.tedu.account.mapper.AccountMapper;
import io.seata.rm.tcc.api.BusinessActionContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
@Component
public class AccountTccActionImpl implements AccountTccAction {
    @Autowired
    private AccountMapper accountMapper;

    @Transactional
    @Override
    public boolean prepareDecreaseAccount(BusinessActionContext ctx, Long userId, BigDecimal money) {
        Account account = accountMapper.selectById(userId);
        if(account.getResidue().compareTo(money)<0){
            throw new RuntimeException("账户金额不足");
        }

        //余额-money，冻结+money
        accountMapper.updateFrozen(userId,account.getResidue().subtract(money),account.getFrozen().add(money));

        if(Math.random()<0.99){
            throw new RuntimeException("模拟异常");
        }

        //保存标识
        ResultHolder.setResult(AccountTccAction.class,ctx.getXid(),"p");
        return true;
    }

    @Transactional
    @Override
    public boolean commit(BusinessActionContext ctx) {
        Long userId = Long.valueOf(ctx.getActionContext("userId").toString());
        BigDecimal money = new BigDecimal(ctx.getActionContext("money").toString());

        //防止重复提交
        if(ResultHolder.getResult(AccountTccAction.class,ctx.getXid())==null){
            return true;
        }

        accountMapper.updateFrozenToUsed(userId,money);

        // 删除标识
        ResultHolder.removeResult(AccountTccAction.class,ctx.getXid());
        return true;
    }
   @Transactional
    @Override
    public boolean rollback(BusinessActionContext ctx) {
       Long userId = Long.valueOf(ctx.getActionContext("userId").toString());
       BigDecimal money = new BigDecimal(ctx.getActionContext("money").toString());

       //防止重复回滚
       if(ResultHolder.getResult(AccountTccAction.class,ctx.getXid())==null){
           return true;
       }

       accountMapper.updateFrozenToResidue(userId, money);
       // 删除标识
       ResultHolder.removeResult(AccountTccAction.class,ctx.getXid());
       return true;
    }
}
